import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { changeEditStatus } from '../../../../reducer/modules/interface.js';
import { Affix, Form, Select, Input, Button, Row, Col, message, DatePicker, Radio } from 'antd';
const FormItem = Form.Item;
const { Option } = Select;
// import EasyDragSort from '../../../../components/EasyDragSort/EasyDragSort.js';
import Editor from 'common/tui-editor/dist/tui-editor-Editor-all.min.js';
// import { formatTime } from '../../../../common.js';
import { fetchMethodData } from '../../../../reducer/modules/dubboMethod'
import ParamsTree from '../../../../components/TreeView/ParamsTree.js';
import {
  getIsTree as paramsGetIsTree,
  getIndexArray as paramsGetIndexArray,
  getFormIndex as paramsGetFormIndex,
  getCellComponent as paramsGetCellComponent,
  jsonToBody as paramsJsonToBody,
  bodyToJson as paramsBodyToJson,
  processFormValues as paramsProcessFormValues
} from '../../../../components/TreeView/Tools/MethodBodyFunc.js';

require('common/tui-editor/dist/tui-editor.min.css'); // editor ui
require('common/tui-editor/dist/tui-editor-contents.min.css'); // editor content
require('./editor.css');
import './MethodEditForm.scss';
import moment from 'moment';


let EditFormContext;
const dataTpl = {
  inbody: {
    name: '',
    name_cn: '',
    field_type: 'String',
    length: '',
    default: '',
    desc: ''
  },
  outbody: {
    name: '',
    name_cn: '',
    field_type: 'String',
    length: '',
    default: '',
    desc: ''
  }
};

@connect(
  state => {
    return {
      curMethod: state.dubboMethod.curMethod,
      curProject: state.dubboProject.currProject
    };
  },
  {
    // fetchMethodBaseData,
    fetchMethodData,
    // upMethodBaseData,
    changeEditStatus
  }
)
class InterfaceEditForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    curMethod: PropTypes.object,
    curProject: PropTypes.object,
    onSubmit: PropTypes.func,
    changeEditStatus: PropTypes.func,
    // fetchMethodBaseData: PropTypes.func,
    fetchMethodData: PropTypes.func
    // upMethodBaseData: PropTypes.func
  };

  initState(curMethod) {
    this.startTime = new Date().getTime();
    let curDataObject = Object.assign({}, curMethod);
    if (typeof (curDataObject.inbody) === 'string') {
      curDataObject.inbody = curDataObject.inbody === '' ? '[]' : curDataObject.inbody;
      curDataObject.inbody = paramsJsonToBody(curDataObject.inbody);
    }
    if (typeof (curDataObject.outbody) === 'string') {
      curDataObject.outbody = curDataObject.outbody === '' ? '[]' : curDataObject.outbody;
      curDataObject.outbody = paramsJsonToBody(curDataObject.outbody);
    }
    if (curDataObject.outbody == undefined) {
      curDataObject.outbody = []
    }
    if (curDataObject.inbody == undefined) {
      curDataObject.inbody = []
    }

    if (curDataObject.ischl === 0) {
      curDataObject.chlEnabled = false
    } else {
      curDataObject.chlEnabled = true
    }

    if (curDataObject.isapi === 0) {
      curDataObject.apiEnabled = false
    } else {
      curDataObject.apiEnabled = true
    }
    // if (curDataObject.inbody == undefined || (curDataObject.inbody && curDataObject.inbody.length === 0)) {
    //   delete curDataObject.inbody;
    // }
    // if (curDataObject.outbody == undefined || (curDataObject.outbody && curDataObject.outbody.length === 0)) {
    //   delete curDataObject.outbody;
    // }

    return Object.assign(
      {
        submitStatus: false,
        inbody: [],
        outbody: [],
        desc: '',
        cname: '',
        mname: '',
        inname: '',
        outname: '',
        onlinedate: '',
        ctime: '',
        etime: '',
        status: '',
        cuserid: '',
        euserid: '',
        infid: '',
        _id: '',
        chlEnabled: true,
        apiEnabled: true
      },
      curMethod, curDataObject
    );
  }

  constructor(props) {
    super(props);
    const { curMethod } = this.props;
    this.state = this.initState(curMethod);
  }

  dateFormat = 'YYYY-MM-DD';
  //编辑功能 tjm
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      submitStatus: true
    });
    try {
      this.props.form.validateFields((err, values) => {
        setTimeout(() => {
          if (this._isMounted) {
            this.setState({
              submitStatus: false
            });
          }
        }, 3000);
        if (!err) {
          values.outbody = values.outbody == undefined ? [] : values.outbody
          values.inbody = values.inbody == undefined ? [] : values.inbody
          if (values.outbody && typeof (values.outbody) === 'object') {
            values.outbody = paramsProcessFormValues(values.outbody);
            values.outbody = paramsBodyToJson(values.outbody);
          }
          if (values.inbody && typeof (values.inbody) === 'object') {
            values.inbody = paramsProcessFormValues(values.inbody);
            values.inbody = paramsBodyToJson(values.inbody);
          }
          values.desc = this.editor.getHtml();
          // 基本信息数据格式转化, 需要和getBasicInfoEdit 中的process保持一致
          if (values.onlinedate && typeof(values.onlinedate) === 'object') {
            values.onlinedate = values.onlinedate.format(this.dateFormat);
          }
          let canSubmit = true
          // 渠道号验证 // TODO: 数据验证独立出来, form和提交数据验证方法统一
          values.chltype = values.ischl === 1 ? values.chltype : undefined
          values.chltype = values.chltype == undefined ? undefined : values.chltype
          if (values.ischl === 1){
            if (!(values.chltype == undefined)) {
              const checkRep = new RegExp(/^[0-9]\d*$/, "g");
              // jctest 
              let projectChltype = this.props.curProject.childbase // 项目渠道号
              projectChltype = projectChltype == undefined ? '' : projectChltype
              const checkRep2 = new RegExp('\^' + projectChltype, "g");

              if (values.chltype == '') {
                canSubmit = false
                message.error("请填写渠道编号")
              } else if (!(values.chltype.length === 6)) {
                canSubmit = false
                message.error("渠道编号长度应为6")
              } else if (!checkRep.test(values.chltype)) {
                canSubmit = false
                message.error("渠道编号必须为数字");
              } else if (!(checkRep2.test(values.chltype))) {
                canSubmit = false
                message.error("渠道编号前两位必须与项目渠道号(" + projectChltype + ")相同")
              } else if (checkRep.test(values.chltype)) {
                canSubmit = true
              }
            } else {
              canSubmit = false
              message.error("请填写渠道编号")
            }
          }
          // default值验证 // TODO: 数据验证独立出来, form和提交数据验证方法统一

          if (canSubmit) {
            this.props.onSubmit(values);
            EditFormContext.props.changeEditStatus(false);
          }
        } else {
          const printErr = ((error) => {
            if (!error) {
            } else if (error.errors) {
              for (var i in error.errors) {
                if (error.errors[i].message) {
                  message.error(error.errors[i].message);
                }
              }
            } else {
              for (var j in error) {
                printErr(error[j]);
              }
            }
          });
          printErr(err);
        }
      });
    } catch (e) {
      console.error(e.message);
      this.setState({
        submitStatus: false
      });
    }
  }

  componentWillMount() {
    this.handleRequest();
  }

  async handleRequest() {
  }

  componentDidMount() {
    EditFormContext = this;
    this._isMounted = true;

    this.editor = new Editor({
      el: document.querySelector('#desc'),
      initialEditType: 'wysiwyg',
      height: '500px',
      initialValue: this.state.desc
    });
  }

  componentWillUnmount() {
    EditFormContext.props.changeEditStatus(false);
    EditFormContext = null;
    this._isMounted = false;
  }

  addParams = (name, data) => {
    let newValue = {};
    data = data || dataTpl[name];
    newValue[name] = [].concat(this.state[name], data);
    this.setState(newValue);
  };

  delParams = (key, name) => {
    let curValue = this.props.form.getFieldValue(name);
    let newValue = {};
    newValue[name] = curValue.filter((val, index) => {
      return index !== key;
    });
    this.props.form.setFieldsValue(newValue);
    this.setState(newValue);
  };

  handleDragMove = name => {
    return data => {
      let newValue = {
        [name]: data
      };
      this.props.form.setFieldsValue(newValue);
      this.setState(newValue);
    };
  };

  // TODO: 批量先不做
  // // 处理批量导入参数
  // handleBulkOk = () => {
  //   let curValue = this.props.form.getFieldValue(this.state.bulkName);
  //   // { name: '', required: '1', desc: '', example: '' }
  //   let newValue = [];

  //   this.state.bulkValue.split('\n').forEach((item, index) => {
  //     let valueItem = Object.assign({}, curValue[index] || dataTpl[this.state.bulkName]);
  //     valueItem.name = item.split(':')[0];
  //     valueItem.example = item.split(':')[1] || '';
  //     newValue.push(valueItem);
  //   });

  //   this.setState({
  //     visible: false,
  //     bulkValue: null,
  //     bulkName: null,
  //     [this.state.bulkName]: newValue
  //   });
  // };

  // TODO:批量先不做
  // // 取消批量导入参数
  // handleBulkCancel = () => {
  //   this.setState({
  //     visible: false,
  //     bulkValue: null,
  //     bulkName: null
  //   });
  // };

  // TODO: 批量先不做
  // showBulk = name => {
  //   let value = this.props.form.getFieldValue(name);

  //   let bulkValue = ``;
  //   value.forEach(item => {
  //     return (bulkValue += item.name ? `${item.name}:${item.example || ''}\n` : '');
  //   });

  //   this.setState({
  //     visible: true,
  //     bulkValue,
  //     bulkName: name
  //   });
  // };

  // TODO: 批量先不做
  // handleBulkValueInput = e => {
  //   this.setState({
  //     bulkValue: e.target.value
  //   });
  // };
  onIsChlChange = (e) => {
    const valueMap = {
      0: false,
      1: true
    };
    this.setState({chlEnabled: valueMap[e.target.value]});
  }

  onIsApiChange = (e) => {
    const valueMap = {
      0: false,
      1: true
    };
    this.setState({apiEnabled: valueMap[e.target.value]});
  }

  getBasicInfoEdit = (data, form) => {
    const process = (data) => {
      if (data.onlinedate == undefined) {
        data.onlinedate = moment().format(this.dateFormat)
      }
      data.chltype = data.ischl === 1 ? data.chltype : undefined
      data.chltype = data.chltype == undefined ? undefined : data.chltype
      return data;
    }
    data = process(data);
    const { getFieldDecorator } = form;
    return (
      <div className="panel-sub">
        <Row className="row">
          <Col span={4} className="colKey">
            方&ensp;法&ensp;名：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('mname', {
                initialValue: data.mname,
                rules: [
                  {
                    required: true,
                    message: "方法名不能为空"
                  }
                ]
              })(<Input placeholder='请输入方法名' />)}
            </FormItem>
          </Col>
          <Col span={4} className="colKey">
            方法名称：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('cname', {
                initialValue: data.cname
              })(<Input placeholder='请输入方法的中文名' />)}
            </FormItem>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4} className="colKey">
            请求类名：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('inname', {
                initialValue: data.inname
              })(<Input placeholder='请输入请求类名' />)}
            </FormItem>
          </Col>
          <Col span={4} className="colKey">
            应答类名：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('outname', {
                initialValue: data.outname
              })(<Input placeholder='请输入应答类名' />)}
            </FormItem>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4} className="colKey">
            渠道交易：
          </Col>
          <Col span={8} className="colValue">
            {/* TODO: 刷新后面的渠道编号是否可用 */}
            <FormItem>
              {getFieldDecorator('ischl', {
                initialValue: data.ischl
              })(
                <Radio.Group onChange={this.onIsChlChange}>
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>

                // <Select onChange = {this.onIsChlChange}>
                //   <Option value={0}>否</Option>
                //   <Option value={1}>是</Option>
                // </Select>
              )}
            </FormItem>
          </Col>
          <Col span={4} className="colKey">
            渠道编号：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('chltype', {
                initialValue: (data.chltype == undefined || data.chltype.length === 0) ? this.props.curProject.chltype : data.chltype
              })(<Input className="chlNumber" placeholder={'请输入渠道编号，渠道编号前置为：' + this.props.curProject.childbase} disabled = {!this.state.chlEnabled}/>)}
            </FormItem>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4} className="colKey">
            Api：
          </Col>
          <Col span={8} className="colValue">
            {/* TODO: 刷新后面的渠道编号是否可用 */}
            <FormItem>
              {getFieldDecorator('isapi', {
                initialValue: data.isapi
              })(
                <Radio.Group onChange={this.onIsApiChange}>
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>
          <Col span={4} className="colKey">
            Api地址：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('url', {
                initialValue: (data.url == undefined || data.url.length === 0) ? this.props.curProject.url : data.url
              })(<Input className="chlNumber" placeholder='请输入Api地址' disabled = {!this.state.apiEnabled}/>)}
            </FormItem>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4} className="colKey">
            状&emsp;&emsp;态：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('status', {
                initialValue: data.status,
                rules: [
                  {
                    required: true,
                    message: "状态不能为空"
                  }
                ]
              })(
                <Select>
                  <Option value={0}>设计中</Option>
                  <Option value={1}>sit测试</Option>
                  <Option value={2}>uat测试</Option>
                  <Option value={3}>已上线</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={4} className="colKey">
            上线时间：
          </Col>
          <Col span={8} className="colValue">
            <FormItem>
              {getFieldDecorator('onlinedate',{
                initialValue: moment(data.onlinedate, this.dateFormat)
              })(
                <DatePicker
                format={this.dateFormat} />
              )}
            </FormItem>
          </Col> 
        </Row>
      </div>
    );
  }

  render() {
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <h2 className="interface-title" style={{ marginTop: 0 }}>
            方法基本信息
          </h2>
          {this.getBasicInfoEdit(Object.assign(this.props.curMethod), this.props.form)}

          <h2 className="interface-title">请求字段设置</h2>
          <div className="panel-sub">
            <ParamsTree
              dataSource={this.state.inbody}
              form={this.props.form}
              getIsTree={paramsGetIsTree}
              treeIndex='inbody'
              getCellComponent={paramsGetCellComponent}
              getIndexArray={paramsGetIndexArray}
              getFormIndex={paramsGetFormIndex}
              topButName='添加请求字段'
            />
          </div>

          <h2 className="interface-title">应答字段设置</h2>
          <div className="panel-sub">
            <ParamsTree
              dataSource={this.state.outbody}
              form={this.props.form}
              getIsTree={paramsGetIsTree}
              treeIndex='outbody'
              getCellComponent={paramsGetCellComponent}
              getIndexArray={paramsGetIndexArray}
              getFormIndex={paramsGetFormIndex}
              topButName='添加应答字段'
            />
          </div>
          {/* ----------- remark ------------- */}

          <h2 className="interface-title">方法描述</h2>
          <div className="panel-sub">
            <FormItem className={'interface-edit-item'}>
              <div>
                <div id="desc" style={{ lineHeight: '20px' }} className="remark-editor" />
              </div>
            </FormItem>
          </div>

          <FormItem
            className="interface-edit-item"
            style={{ textAlign: 'center', marginTop: '16px' }}
          >
            <Affix offsetBottom={0}>
              <Button
                className="interface-edit-submit-button"
                disabled={this.state.submitStatus}
                size="large"
                htmlType="submit"
                onClick={this.handleSubmit}
              >
                保存
              </Button>
            </Affix>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export default Form.create({
  onValuesChange() {
    EditFormContext.props.changeEditStatus(true);
  }
})(InterfaceEditForm);
